package com.example.mysocketdemo;


import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.googlecode.tesseract.android.TessBaseAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity implements ClientConnector.ConnectLinstener {

    private static final String TAG = "MainActivity";
    private EditText mAuthDevice;
    private EditText mReceiveDevice;
    private EditText mSendingMsg;
    private HandlerThread mHandlerThread;
    private Handler mHandler;
    private ClientConnector mConnector;
    //IDE自带的模拟器是10.0.0.2
    //192.168.1.200
    private String mDstName = "192.168.1.200";
    private int mDstPort = 5858;
    private ListView mListView;
    private ArrayAdapter mAdapter;
    private List<String> mData;
    private String mSampleDirPath;
    private TimerTask mTimerTask;
    private Timer mTimer;
    boolean hasStart = false;
    private int SWITCHDEVICE = 0;
    Bitmap bitmap;
    private int REQUEST_MEDIA_PROJECTION = 1;
    private int result = 0;
    private Intent intent = null;
    private MyReceiver receiver=null;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //注册EventBus
//        EventBus.getDefault().register(this);

        /*if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_CALENDAR,
                            Manifest.permission.WRITE_CALENDAR,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);
        }*/

        /*File sampleDir = Environment.getExternalStorageDirectory();
        if (sampleDir.canWrite()) {
            mSampleDirPath = sampleDir.getAbsolutePath() + File.separator + "MCPInDoor";
        }

        if (mSampleDirPath != null) {
            sampleDir = new File(mSampleDirPath);
        }
        if (sampleDir != null && !sampleDir.exists()) {
            if (!sampleDir.mkdirs()) {
                Log.e(TAG, "onCreate: ----------------- 创建失败");
            }
        }*/

        initView();
        initData();
        //注册广播接收器
        receiver=new MyReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.example.mysocketdemo.Service1");
        getApplicationContext().registerReceiver(receiver,filter);
        MediaProjectionManager mMediaProjectionManager = (MediaProjectionManager) getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
        ((ShotApplication)getApplication()).setMediaProjectionManager(mMediaProjectionManager);
        Service1 service1 = new Service1();
        service1.setOnShotFinishListener(new Service1.OnShotFinishListener() {
            @Override
            public void onShotFinishListener(Bitmap bitmap) {
                mBitmap = bitmap;
                orcPicToText();
            }
        });
        path = Environment.getExternalStorageDirectory().getAbsoluteFile().getAbsolutePath();
        mBaseAPI = new TessBaseAPI();//初始化需要耗时，可以启动时程序时，预初始化
        /*new Thread(){
            @Override
            public void run() {
            }
        }.start();*/
        try {
            mBaseAPI.init(path + File.separator, "chi_sim");
        } catch (Exception e) {
            Log.e("AAAAA", e.getMessage());
        }

        Intent intent = new Intent(this,Service1.class);
        startService(intent);
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void run() {
                        /*View view = getWindow().getDecorView();
                        view.setDrawingCacheEnabled(true);
                        view.buildDrawingCache();
                        bitmap = view.getDrawingCache();
                        Rect frame = new Rect();
                        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                        int toHeight = frame.top;
                        bitmap = Bitmap.createBitmap(bitmap, 0, 100, 720, 200);
                        try {
                            FileOutputStream fout = new FileOutputStream("mnt/sdcard/test.png");
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        view.setDrawingCacheEnabled(false);*/
                        EventBus.getDefault().post(new FIrstEvent("FirstEvent clicked"));
                    }
                });

            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask,2000);
    }

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle=intent.getExtras();
            int count=bundle.getInt("count");
//            mBitmap = bundle.getParcelable("C");
            byte [] bis=intent.getByteArrayExtra("bitmap");
            mBitmap=BitmapFactory.decodeByteArray(bis, 0, bis.length);
            orcPicToText();
//            textView.setText(count+"");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(FIrstEvent event) {

        String msg = "onEventMainThread收到了消息：" + event.getMsg();
        Log.e("getMsg", msg);
//        tv.setText(msg);
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //反注册EventBus
//        EventBus.getDefault().unregister(this);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode != Activity.RESULT_OK) {
                return;
            }else if(data != null && resultCode != 0){
                Log.i(TAG, "user agree the application to capture screen");
                //Service1.mResultCode = resultCode;
                //Service1.mResultData = data;
                result = resultCode;
                intent = data;
                ((ShotApplication)getApplication()).setResult(resultCode);
                ((ShotApplication)getApplication()).setIntent(data);
                Intent intent = new Intent(getApplicationContext(), Service1.class);
                startService(intent);
                Log.i(TAG, "start service Service1");

                MainActivity.this.finish();
            }
        }
    }

    private void initView() {
        mAuthDevice = (EditText) findViewById(R.id.et_auth_device);
        mReceiveDevice = (EditText) findViewById(R.id.et_receive_device);
        mSendingMsg = (EditText) findViewById(R.id.et_send_message);
        mListView = (ListView) findViewById(R.id.listview);
    }

    private void initData() {
        mHandlerThread = new HandlerThread("MainActivity", android.os.Process.THREAD_PRIORITY_BACKGROUND);
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper());
        mConnector = new ClientConnector(mDstName, mDstPort);
        mConnector.setOnConnectLinstener(this);
        mData = new ArrayList<>();
        mAdapter = new ArrayAdapter(this, R.layout.item, R.id.tv_text, mData);
        mListView.setAdapter(mAdapter);
        mHandler.post(new ConnectRunnable());

        backToHome();
    }

    private void execShellCmd(String cmd) {
        try {
            // 申请获取root权限
            Process process = Runtime.getRuntime().exec("su");
            // 获取输出流
            OutputStream outputStream = process.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(
                    outputStream);
            dataOutputStream.writeBytes(cmd);
            dataOutputStream.flush();
            dataOutputStream.close();
            outputStream.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    public void connectServer(View view) {

        mHandler.post(new ConnectRunnable());
    }

    @Override
    public void onReceiveData(final String data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mData.add(data);

                SWITCHDEVICE++;

                /*switch (SWITCHDEVICE % 3) {
                    case 1:
                        //扫地机器人
                        backToHome();

                        break;
                    case 2:
                        //风扇
                        backToHome();
                        break;
                    case 0:
                        //灯泡
                        backToHome();

                        break;
                }*/

                if (data.contains("START")) {
                    //截图
                    EventBus.getDefault().post(new FIrstEvent("FirstEvent clicked"));
                    /*if (!hasStart) {
                        hasStart = true;
                        execShellCmd("input tap " + 360 + " " + 1200);
                    }*/
                } else if (data.contains("STOP")) {
                    EventBus.getDefault().post(new FIrstEvent("FirstEvent clicked"));
                    /*if (hasStart) {
                        hasStart = false;
                        execShellCmd("input tap " + 360 + " " + 1200);
                        mTimerTask = new TimerTask() {
                            @Override
                            public void run() {
                                execShellCmd("input tap " + 400 + " " + 1200);
                            }
                        };
                        mTimer = new Timer();
                        mTimer.schedule(mTimerTask, 800);
                    }*/

                } else if (data.contains("AT+OK")) {
                    //连接成功返回通知
                    if (mTimerTask != null) {
                        mTimerTask.cancel();
                    }
                    if (mTimer != null) {
                        mTimer.cancel();
                    }
                } else if (data.contains("HOME")) {
//                    backToHome();
                    EventBus.getDefault().post(new FIrstEvent("FirstEvent clicked"));
                }

                mAdapter.notifyDataSetChanged();
//                Toast.makeText(MainActivity.this, "data=" + data, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String path;
    private TessBaseAPI mBaseAPI;
    private Bitmap mBitmap;
    //识别图片中的文字
    private void orcPicToText() {

        File f = new File(path+"/tessdata") ;
        if(!f.exists()){
            Toast.makeText(this,"请先下载好语言包置于sd/tessdata目录",Toast.LENGTH_SHORT).show();
            return;
        }

        /*final int btnId = mRadioGroup.getCheckedRadioButtonId();
        final int resId ;
        if(R.id.rb_idCard==btnId){
            resId = R.drawable.idcard;
        }else if(R.id.rb_bankNumber==btnId){
            resId = R.drawable.bank_number;
        }else{
            resId = R.drawable.tet_info;
        }

        mProbar.setVisibility(View.VISIBLE);*/
        new Thread() {
            @Override
            public void run() {

//                Bitmap bitmap = getBitmap(resId);
                if (mBitmap == null) {
                    mHandler0.sendEmptyMessage(1);
                } else {
                    mBaseAPI.setImage(mBitmap);
                    //根据Init的语言，获得ocr后的字符串
                    String t = mBaseAPI.getUTF8Text();//耗时操作
                    Message obtain = Message.obtain();
                    obtain.what = 0;
                    obtain.obj = t;
                    mHandler0.sendMessage(obtain);
                }
            }
        }.start();
    }

    private Handler mHandler0 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    String s = (String) msg.obj;
                    if (s.equals("清扫")) {
                        //当前是停止状态
                        if (!hasStart) {
                            hasStart = true;
                            execShellCmd("input tap " + 360 + " " + 1200);
                        }
                    } else if (s.equals("暂停")){
                        //“暂停”
                        //当前正在清扫
                        if (hasStart) {
                            hasStart = false;
                            execShellCmd("input tap " + 360 + " " + 1200);
                            mTimerTask = new TimerTask() {
                                @Override
                                public void run() {
                                    execShellCmd("input tap " + 400 + " " + 1200);
                                }
                            };
                            mTimer = new Timer();
                            mTimer.schedule(mTimerTask, 800);
                        }
                    }
                    /*if (!TextUtils.isEmpty(s)) {
                        mProbar.setVisibility(View.GONE);
                        mTvInfo.setText(s);
                        //释放bitmap
                        mBaseAPI.clear();
                    } else {
                        mProbar.setVisibility(View.GONE);
                        Toast.makeText(MainActivity.this, "识别图片内容失败", Toast.LENGTH_SHORT).show();
                    }*/

                    break;
                case 1:
                    Toast.makeText(MainActivity.this, "读取图片失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private Bitmap getBitmap(int id) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeResource(getResources(), id);
        } catch (Exception e) {
            return null;
        }
        return bitmap;
    }


    //截取屏幕的指定位置


    private void backToHome() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    private class ConnectRunnable implements Runnable {

        @Override
        public void run() {
            try {

                Log.e("ConnectRunnable", "连接socket....");
                mConnector.connect();
                mConnector.auth("A");
//                try {
//                } catch (IOException e) {
//                }
            } catch (IOException e) {
                TimerTask timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        mHandler.post(new ConnectRunnable());
                    }
                };
                Timer timer = new Timer();
                timer.schedule(timerTask, 5000, 5000);
                e.printStackTrace();
            }
        }
    }

    public void authClient(View view) {

        String auth = mAuthDevice.getText().toString().trim();
        if (TextUtils.isEmpty(auth)) {
            Toast.makeText(this, "认证信息不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            mConnector.auth(auth);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(View view) {
        String receiver = mReceiveDevice.getText().toString().trim();
        String msg = mSendingMsg.getText().toString().trim();
        if (TextUtils.isEmpty(msg) || TextUtils.isEmpty(receiver)) {
            Toast.makeText(this, "信息不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
//            mData.add(msg);
            mConnector.send(receiver, msg);
//            mAdapter.notifyDataSetChanged();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void disconnectServer(View view) {
        try {
            mConnector.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
